import WebSocket from 'ws';
import { ConnectionConfig } from '../ConfigLoader';
import MessageHandler from '../MessageHandler';

export default class WebSocketClient {
  private client?: WebSocket;
  private handler: MessageHandler;
  private url: string;

  constructor(private config: ConnectionConfig, handler: MessageHandler) {
    this.handler = handler;
    this.url = `ws://${config.ws.client.host}`;
    if (config.token != null) {
      this.url += `?access_token=${config.token}`;
    }
  }

  connect() {
    this.client = new WebSocket(this.url);

    this.client.on('open', () => {
      this.handler.onConnected('client', this.url);
    });

    this.client.on('message', (message) => {
      this.handler.processMessage(message, 'client', this.client);
    });

    this.client.on('error', (err) => {
      console.error('[WS Client] 连接错误:', err.message);
    });

    this.client.on('close', (code: number, reason: Buffer) => {
      const reasonStr = reason.toString();
      console.log(`[WS Client] 连接已关闭，代码: ${code}, 原因: ${reasonStr}`);
      this.handleReconnect();
    });
  }

  private handleReconnect() {
    if (this.client) {
      console.log('[WS Client] 尝试重新连接...');
      setTimeout(() => {
        this.connect();
      }, 5000); // 5秒后重试
    }
  }
}